<!--
 * @Description: 上传组件
 * @Author: jiansheng
 * @Date: 2024-11-17 11:38:33
-->

<template>
  <div>
    <van-uploader
      v-model="fileList"
      :accept="accept"
      :after-read="afterRead"
      :max-count="count"
      :max-size="maxSizeNum"
      :multiple="multiple"
      @delete="onDelete"
      @oversize="onOversize"
      :preview-image="isPreview"></van-uploader>
    <p class="notice">{{ notice }}</p>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  props: {
    reviewList: { type: Array, default: () => [] },
    accept: { type: String, default: 'image/png, image/jpeg, image/bmp, image/webp' },
    count: { type: Number, default: 12 }, // 最多上传文件个数
    maxSize: { type: Number, default: 2 }, //
    isPreview: { type: Boolean, default: true }, // 上传完成后是否展示预览图
    single: { type: Boolean, default: false }, // $emit的值为单次
    multiple: { type: Boolean, default: true },
    notice: { type: String, default: '仅限.jpg,.jpeg,.png图片格式，大小在5M以内' }
  },
  data() {
    return {
      fileList: [],
      finishedCount: 0,
      outFileIds: []
    }
  },
  computed: {
    maxSizeNum() {
      return this.maxSize * 1024 * 1024
    }
  },
  watch: {
    reviewList: {
      immediate: true,
      handler(ary) {
        if (ary && ary.length) this.fileList = ary
        else this.fileList = []
      }
    }
  },
  methods: {
    onOversize(file) {
      console.log(file)
      this.$toast('文件大小不能超过' + this.maxSize + 'M')
    },
    onDelete() {
      if (this.fileList.length) {
        this.$emit('success', this.fileList.map(i => i.id).join())
      } else {
        this.$emit('success', '')
      }

      return true
    },
    async afterRead(e) {
      // 显示上传中的loading提示
      this.$toast.loading({
        message: '上传中...',
        forbidClick: true,
        duration: 0,
        overlay: true
      })

      let readyUpload = []

      // 判断传入的参数类型，将文件加入到readyUpload数组
      if (Array.isArray(e)) {
        readyUpload = e.map(fileItem => fileItem.file) // 使用 map 处理文件
      } else {
        readyUpload.push(e.file)
      }

      // 记录上传完成的文件数
      this.finishedCount = 0

      // 使用 for...of 循环逐个处理文件，确保按顺序上传
      for (const myfile of readyUpload) {
        try {
          // 创建 FormData 实例并添加文件
          const formdata = new FormData()
          formdata.append('file', myfile, myfile.name)

          // 发起文件上传请求，并使用 await 等待请求完成
          const res = await axios.post(process.env.VUE_APP_BASE_API + '/dify/report/upload', formdata, {
            headers: {
              'Content-Type': 'multipart/form-data',
              Authorization: `Bearer ${localStorage.getItem('userToken')}`
            }
          })

          // 上传成功，处理返回结果
          if (res.data.code === 200) {
            this.finishedCount++
            this.fileList = [...this.fileList.filter(i => i.id), { id: res.data.id, url: res.data.url }]
          }
        } catch (err) {
          console.log('上传报错', err)
        }

        // 如果所有文件都上传完成，清除loading提示
        if (this.finishedCount === readyUpload.length) {
          this.$toast.clear()
          this.finishedCount = 0 // 重置上传完成计数器
          this.$emit('success', this.fileList.map(i => i.id).join())
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
// .camara {
//   width: 70px;
//   height: 70px;
//   border-radius: 2px;
//   border: 1px dashed rgba(216, 216, 216, 1);
//   text-align: center;
//   img {
//     margin-top: 25px;
//   }
// }
.notice {
  color: #ccc;
  line-height: 1.2;
}
</style>
